﻿/**
* 
* @author Chen
* @version 1.0
*
*/
angular.module("ng-unvs-loader", ["ng-unvs-utils"])
.service("$loader", ["$page", function ($loader) {
    return {
        $getRootTemplate: function () {
            if (!window.top.ngW8.$config.$loaderPath) {
                throw ("template path was not found, call $setRootTemplatePath");
            }
            return window.top.ngW8.$config.$loaderPath;
        },
        $getConfig: function (txt) {
            var i = txt.indexOf("<body>") + 6;
            var j = txt.indexOf("</body>", i);
            var txtBody = txt.substring(i, j);
            i = txtBody.indexOf("<script>");
            j = txtBody.indexOf("</script>");
            var txtScript = undefined;
            if (i > -1) {
                j += 9;
                txtScript = txtBody.substring(i, j);
            }

            txtBody = txtBody.replace(txtScript, "");
            txtBody = window.top.ngW8.$Funcs.$string.$clean("<!-- Visual Studio Browser Link -->", "<!-- End Browser Link -->", txtBody);
            if (txtScript) {
                txtScript = txtScript.replace("<script>", "").replace("</script>", "");
            }
            while (txtBody.indexOf("\r\n") > -1) {
                txtBody = txtBody.replace("\r\n", "");
            }
            return {
                html: txtBody,
                script: txtScript
            };
        },

        $apply: function ($scope, item, callback) {
            var config = item.config;
            var scope = $scope.$new(true);
            if (!window.top.$rootAppScope) {
                window.top.$rootAppScope = $scope.$root;

            }
            if (!$scope.$root.$scopeList) {
                $scope.$root.$scopeList = [];
            }
            $scope.$root.$scopeList.push(scope);
            item.scope = scope;

            scope.$$$ready = function (callback) {
                scope.$$$onReadyHandler = callback;
            };
            scope.$$$templatePath = item.root + item.path;
            scope.$$$rootPath = item.root;
            scope.$$$page = item.path.replace(".html", "");
            scope.$$$path = item.path;
            scope.$$$done = function () {
                if (!config) return;
                if (!config.html) return;
                var ele = $("<div>" + config.html + "</div>");
                try {
                    $compile($(ele).contents())(scope);
                    scope.$elements = ele.children();
                    scope.$find = function (selector) {
                        return $(selector, scope.$elements);
                    };
                }
                catch (ex) {
                    throw (ex);
                }

                if (config.script &&
                    (config.script != null) &&
                    (config.script != "")) {


                    scope.$$$readyHandler = Function("", config.script);
                    scope.$$$readyHandler(scope);

                }

                callback(scope, $(ele).children());
                if (scope.$$$onReadyHandler) {
                    scope.$$$onReadyHandler(scope);
                };
                if (scope.$root.$$phase == null) {
                    scope.$apply();
                }

            }

            if (window.top.ngW8.$eventsHandler.$onCreateNewScope) {
                window.top.ngW8.$eventsHandler.$onCreateNewScope(scope);
            }
            else {

                scope.$$$done();
                return item;
            }
            //if (callback) {
            //    callback(scope, scope.$elements);

            //}

        },
        $key: function (path) {
            var ret = path;
            while (ret.indexOf('/') > -1) {
                ret = ret.replace('/', '$_splash_$');
            }
            while (ret.indexOf('.') > -1) {
                ret = ret.replace('.', '$_dot_$');
            }
            return ret;
        },
        $get: function (path) {
            return $loader(path);
        },
        $load: function ($scope, path, callback, nonHistory) {
            var loadPath = path;
            if (!window.top.ngW8.$config.$noCache) {
                loadPath = path + "?t=" + (new Date()).getUTCMilliseconds();
            }
            var me = this;
            if (!window.top.$pagesIntance) {
                window.top.$pagesIntance = {};
            }
            if (!window.top.$pagesIntance[path]) {
                window.top.$pagesIntance[path] = {
                    root: me.$getRootTemplate(),
                    path: path
                };
                var root = me.$getRootTemplate();
                $http.get(root + "/" + loadPath)
                     .success(function (res) {

                         try {
                             var config = me.$getConfig(res);
                             window.top.$pagesIntance[path].config = config;
                             me.$apply($scope, window.top.$pagesIntance[path], callback);
                         }
                         catch (ex) {
                             throw (ex);
                         }


                     })
                     .then(function (res) {
                     },
                     function (error) {
                         throw (error);
                         if (window.top.$onLoadPageErrorHandler) {
                             window.top.$onLoadPageErrorHandler({
                                 path: path,
                                 error: error
                             });
                         }
                     });
            }
            else {
                if (window.top.$pagesIntance[path]) {
                    if (window.top.$pagesIntance[path].scope) {
                        window.top.$pagesIntance[path].scope.$destroy();
                    }

                    me.$apply($scope, window.top.$pagesIntance[path], callback);
                }

            }
        }
    }
}]);